package list

import (
	"errors"
	"fmt"
)

//普通单链表

type ListNode struct {
	Val  int
	Next *ListNode
}

func (head *ListNode) Append(newNode *ListNode) {
	//在链表结尾添加元素
	for ; head.Next != nil; head = head.Next {
	}
	head.Next = newNode
}

func New() *ListNode {
	return &ListNode{}
}

func (head *ListNode) Insert(val int) {
	//按序从小到大添加
	//不能用二分查找来向链表插入值 可以使用跳跃表
	for ; head.Next != nil; head = head.Next {
		if head.Next.Val > val {
			head.Next = &ListNode{
				Val:  val,
				Next: head.Next,
			}
			return
		}
	}

	head.Next = &ListNode{
		Val: val,
	}

}

func (head *ListNode) Find(value int) (index int, node *ListNode) {
	//返回值等于指定节点的地址

	for ; head != nil; head = head.Next {
		index++
		if head.Val == value {
			return index, head
		}
	}
	return 0, nil

}

func (head *ListNode) PrintList() {
	for ; head.Next != nil; head = head.Next {
		fmt.Printf("%d -> ", head.Val)
	}
	fmt.Println(head.Val)
}

func (head *ListNode) Delete(value int) error {
	//
	for ; head.Next != nil; head = head.Next {
		if head.Next.Val == value {
			head.Next = head.Next.Next
			return nil
		}
	}
	return errors.New("No element deleted")
}
